package com.vates.vsp.dao.implementacion;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.vates.vsp.dao.DaoBaseHotel;
import com.vates.vsp.entidades.Hotel;
import com.vates.vsp.entidades.TipoHabitacion;

@Repository(value = "hotelDao")
public class HotelDao implements DaoBaseHotel {

	@PersistenceContext(unitName = UNIT_NAME)
	private EntityManager em;

	public void setEm(EntityManager em) {
		this.em = em;
	}

	@Transactional
	public void guardar(Hotel hotel) {
		if (hotel != null)
			em.merge(hotel);
	}

	@Transactional
	public void eliminar(Hotel hotel) {
		if (hotel != null) {
			em.remove(em.merge(hotel));
		}
	}

	@Transactional
	public Hotel buscarPorId(Long id) {
		try {
			TypedQuery<Hotel> q = em.createQuery(
					"SELECT h FROM Hotel h WHERE h.idHotel= :id", Hotel.class);
			return q.setParameter("id", id).getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

	@Transactional
	public Hotel buscarPorNombre(String nombre) {
		try {
			TypedQuery<Hotel> q = em.createQuery(
					"SELECT h FROM Hotel h WHERE h.nombre= :nombre",
					Hotel.class);
			return q.setParameter("nombre", nombre).getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

	@Transactional
	public List<Hotel> buscarTodos() {
		try {
			return em.createQuery("SELECT h FROM Hotel h", Hotel.class)
					.getResultList();
		} catch (NoResultException e) {
			return null;
		}
	}

	@Transactional
	public List<Hotel> buscarPorLocalidad(String localidad) {
		try {
			TypedQuery<Hotel> q = em
					.createQuery(
							"SELECT h FROM Hotel h WHERE h.direccion.localidad= :localidad",
							Hotel.class);
			q.setParameter("localidad", localidad);
			return q.getResultList();
		} catch (NoResultException e) {
			return null;
		}
	}
	
	 @Transactional
     public void eliminar(TipoHabitacion tipoHabitacion) {
             if (tipoHabitacion != null) {
                     em.remove(em.merge(tipoHabitacion));
             }
     }
	 
	 @Transactional
	 public TipoHabitacion buscarTipoHabitacionPorId(Long idTipoHab) {
		 TypedQuery<TipoHabitacion> q = em.createQuery("SELECT th FROM TipoHabitacion th WHERE th.idTipoHab= :id", TipoHabitacion.class);
		 q.setParameter("id", idTipoHab);
		 return q.getSingleResult();
	 }
}
